package com.wmh.baseservice.admin.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wmh.baseservice.admin.entity.AdViewRecord;
import com.wmh.baseservice.admin.mapper.AdViewRecordMapper;
import com.wmh.baseservice.admin.pojo.vo.viewRecord.AdViewRecordAddReqVO;
import com.wmh.baseservice.admin.pojo.vo.viewRecord.AdViewRecordUpdateReqVO;
import com.wmh.baseservice.admin.service.AdViewRecordService;

import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.structure.LambdaQueryWrapperX;
import com.wmh.baseservice.common.utils.web.UserUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 谢骏
 * @description 针对表【ad_view_record】的数据库操作Service实现
 * @createDate 2023-07-16 13:45:26
 */
@Service
public class AdViewRecordServiceImpl extends ServiceImpl<AdViewRecordMapper, AdViewRecord>
        implements AdViewRecordService {

    @Resource
    private UserUtil userUtil;

    @Override
    public void add(AdViewRecordAddReqVO reqVO) {
        checkNameUniqueness(null,reqVO.getName(),reqVO.getComponentUrl());
        AdViewRecord entity = new AdViewRecord();
        entity.setAdId(userUtil.getId()).setName(reqVO.getName())
                .setComponentUrl(reqVO.getComponentUrl()).setJsonParam(reqVO.getJsonParam());
        baseMapper.insert(entity);
    }

    @Override
    public void delete(List<Long> ids) {
        baseMapper.delete(new LambdaQueryWrapperX<AdViewRecord>()
                .eq(AdViewRecord::getAdId,userUtil.getId())
                .in(AdViewRecord::getId,ids));
    }

    @Override
    public void update(AdViewRecordUpdateReqVO reqVO) {
        AdViewRecord oldEntity = checkExist(reqVO.getId());
        checkNameUniqueness(reqVO.getId(), reqVO.getName(), oldEntity.getComponentUrl());
        AdViewRecord newEntity = new AdViewRecord()
                .setId(reqVO.getId())
                .setAdId(userUtil.getId())
                .setName(reqVO.getName())
                .setJsonParam(reqVO.getJsonParam());
        baseMapper.updateById(newEntity);
    }


    private void checkNameUniqueness(Long id, String name, String componentUrl) {
        AdViewRecord adViewRecord = baseMapper.selectOne(new LambdaQueryWrapperX<AdViewRecord>()
                .neIfPresent(AdViewRecord::getId, id)
                .eq(AdViewRecord::getAdId, userUtil.getId())
                .eq(AdViewRecord::getName, name)
                .eq(AdViewRecord::getComponentUrl, componentUrl)
        );
        if (adViewRecord != null) {
            throw new ServiceException("名称不能重复");
        }
    }

    private AdViewRecord checkExist(Long id){
        AdViewRecord r = baseMapper.selectById(id);
        if (r == null){
            throw new ServiceException("当前数据不存在");
        }
        return r;
    }
}




